import {
  Col,
  Row,
  Button,
  Space,
  Typography,
  Spin,
  Table,
  Modal,
  message,
  Upload,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import IconFont from "../../../../../../assets/ICON";
import { getFindDevice, deleteDevice } from "../../../ServeApi";
import {
  exportFile,
  getUserInfo,
  importFile,
} from "../../../../../../utils/common";
import {
  AjaxData,
  columnsDataCLass,
} from "../../../../../../data/interface/publicInterface";
import * as React from "react";
import { ergodicListAddIdToKey } from "../../../../../../utils/common";
import ModalDetail from "../ModalDetail";
const { Text } = Typography;
export interface DeviceTableProps {
  devVal: string;
}

export interface DeviceTableState {
  loading: boolean;
  selectedRowKeys: string[];
  visible: boolean;
  initValue: any;
  devVal: string;
}

class DeviceTable extends React.Component<DeviceTableProps, DeviceTableState> {
  private columns: columnsDataCLass[] = [
    {
      key: "no",
      title: "编号",
      dataIndex: "no",
    },
    {
      key: "name",
      title: "设备名称",
      dataIndex: "name",
    },
    {
      key: "devAdd",
      title: "设备地址",
      dataIndex: "devAdd",
    },
    {
      key: "installAdd",
      title: "安装位置",
      dataIndex: "installAdd",
    },
    {
      key: "ipAdd",
      title: "网关IP",
      dataIndex: "ipAdd",
    },
    {
      key: "longitude",
      title: "经度",
      dataIndex: "longitude",
    },
    {
      key: "latitude",
      title: "纬度",
      dataIndex: "latitude",
    },
    {
      key: "contacts",
      title: "责任人",
      dataIndex: "contacts",
    },
    {
      key: "phone",
      title: "联系电话",
      dataIndex: "phone",
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",

      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.onEditDevice(record);
                }}
              >
                <IconFont
                  type="icon_form_bianji"
                  style={{ color: "#FBB10B" }}
                />
                <Text>编辑</Text>
              </span>

              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.onDeleteDevice(record);
                }}
              >
                <IconFont
                  type="icon_form_shanchu"
                  style={{ color: "#FF6B6B" }}
                />
                <Text>删除</Text>
              </span>
            </Space>
          </>
        );
      },
    },
  ];
  private dataSouce: any[] = [];
  private pageIndex: number = 1;
  private pageSize: number = 20;
  private total: number = 0;
  state = {
    loading: false,
    selectedRowKeys: [],
    visible: false,
    initValue: null,
    devVal: "",
  };
  shouldComponentUpdate(np: DeviceTableProps, ns: DeviceTableState) {
    if (np.devVal !== this.props.devVal) {
      this.setState({ devVal: np.devVal });
      setTimeout(() => {
        this.getDataList();
      });
    }
    return true;
  }
  componentWillMount() {
    this.getDataList();
  }
  /**操作 */
  //选择操作的设备
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRowKeys: selectedRowKeys,
    });
  };
  //弹窗确认
  handleCancel() {
    this.setState({ visible: false, initValue: null });
  }
  //弹窗取消
  handleOk() {
    this.setState({ visible: false, initValue: null });
    this.getDataList();
  }
  //新增
  onAddDevice() {
    this.setState({ visible: true });
  }
  //编辑
  onEditDevice(record: any) {
    this.setState({ visible: true, initValue: record });
  }
  //批量删除
  onDeleteBatchDevice() {
    let { selectedRowKeys } = this.state;
    let pream: string[] = selectedRowKeys;
    let _this = this;
    if (selectedRowKeys.length) {
      Modal.confirm({
        title: "是否确认删除设备",
        onOk: () => {
          _this.deleteDevice(pream);
        },
      });
    } else {
      message.error("请选择设备");
    }
  }
  onDeleteDevice(record: any) {
    let pream: string[] = [record.id];
    let _this = this;
    Modal.confirm({
      title: "是否确认删除设备",
      onOk: () => {
        _this.deleteDevice(pream);
      },
    });
  }
  /**请求数据 */
  //获取分页数据
  async getDataList() {
    let _this = this;
    try {
      let pream = {
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        likeStr: this.state.devVal,
      };
      let res: any = await getFindDevice(JSON.stringify(pream));
      let json: AjaxData = res;
      if (json.success) {
        //ergodicListAddIdToKey
        _this.dataSouce = ergodicListAddIdToKey(json.data.records);
        _this.total = json.data.total;
        this.forceUpdate();
      }
    } catch (error) {
      Modal.error({
        title: error,
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
    }
  }
  //删除设备
  async deleteDevice(arr: string[]) {
    let pream = {
      deviceIdList: arr,
    };
    try {
      let res: any = await deleteDevice(JSON.stringify(pream));
      let json: AjaxData = res;
      if (json.success) {
        this.getDataList();
      }
    } catch (error) {
      Modal.error({ title: "删除失败，请刷新页面" });
    }
  }
  //模板下载
  downTemplate() {
    exportFile("/api/ems/safety/device/downTemplate", "", "设备导入模板.xlsx");
  }
  render() {
    let { selectedRowKeys } = this.state;
    let rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div className="rowcon_body">
        <Row>
          <Col span={24} className="subject">
            <div className="operation">
              <Button
                type="primary"
                className="increased"
                size="middle"
                icon={<PlusOutlined />}
                onClick={() => {
                  this.onAddDevice();
                }}
              >
                新增
              </Button>
              <Button
                type="primary"
                className="addoperating"
                size="middle"
                icon={<IconFont type="icon_form_shanchu" />}
                onClick={() => {
                  this.onDeleteBatchDevice();
                }}
              >
                删除
              </Button>
              <Button
                type="primary"
                className="export"
                size="middle"
                onClick={this.downTemplate}
                icon={<IconFont type="icon_xiazai" />}
              >
                模板下载
              </Button>
              <Upload
                accept=".xlsx"
                showUploadList={false}
                beforeUpload={(file) => {
                  const formData = new FormData();
                  formData.append("file", file);
                  formData.append("peId", getUserInfo("peId"));
                  formData.append("loginName", getUserInfo("loginName"));
                  importFile(
                    "/wj/ems/safety/device/upload/importExcelDevice",
                    formData,
                    this,
                    (result) => {
                      if (result.success) {
                        this.getDataList();
                      }
                    },
                    (err) => {
                      // this.setState({ resultVisible: false });
                    }
                  );
                  return false;
                }}
              >
                <Button
                  type="primary"
                  className="export"
                  size="middle"
                  icon={<IconFont type="icon_daoru" />}
                >
                  导入
                </Button>
              </Upload>
              {/* <Button
                type="primary"
                className="export"
                size="middle"
                icon={<IconFont type="icon_daoru" />}
              >
                导入
              </Button> */}
              {/* <Button
                type="primary"
                className="export"
                size="middle"
                icon={<IconFont type="icon_daochu" />}
              >
                导出
              </Button> */}
            </div>
          </Col>
          <Col span={24}>
            <Spin spinning={this.state.loading}>
              <Table
                columns={this.columns}
                dataSource={this.dataSouce}
                rowSelection={rowSelection}
                pagination={{
                  pageSize: this.pageSize,
                  total: this.total,
                  current: this.pageIndex,
                  onChange: (page: number) => {
                    this.pageIndex = page;
                    this.getDataList();
                  },
                }}
                sticky
              ></Table>
            </Spin>
          </Col>
        </Row>
        <ModalDetail
          visible={this.state.visible}
          defaultValue={this.state.initValue}
          onOk={() => {
            this.handleOk();
          }}
          onCancel={() => {
            this.handleCancel();
          }}
        />
      </div>
    );
  }
}

export default DeviceTable;
